import { NextResponse, NextRequest } from 'next/server';
import { prisma } from '@/lib/db';
import { auth } from '@/auth';

// GET /api/notifications - 获取当前用户的通知
export async function GET(request: NextRequest) {
  try {
    const session = await auth();

    if (!session?.user?.id) {
      return NextResponse.json({ error: '未授权' }, { status: 401 });
    }

    const userId = session.user.id;
    
    // 从查询参数获取过滤条件
    const { searchParams } = new URL(request.url);
    const isRead = searchParams.get('isRead');
    const limit = searchParams.get('limit') ? parseInt(searchParams.get('limit')!, 10) : 10;
    
    // 构建查询条件
    const whereCondition: any = { userId };
    
    if (isRead !== null) {
      whereCondition.read = isRead === 'true';
    }

    // 获取用户通知
    const notificationRecipients = await prisma.notificationRecipient.findMany({
      where: whereCondition,
      orderBy: { notification: { createdAt: 'desc' } },
      take: limit,
      include: {
        notification: true,
      },
    });

    // 格式化响应数据
    const notifications = notificationRecipients.map(({ notification, read }) => ({
      id: notification.id,
      type: notification.type,
      title: notification.title,
      content: notification.content,
      createdAt: notification.createdAt,
      read,
    }));

    return NextResponse.json(notifications);
  } catch (error) {
    console.error('获取通知失败:', error);
    return NextResponse.json(
      { error: '获取通知时出错' },
      { status: 500 }
    );
  }
}

// POST /api/notifications/mark-all-read - 标记所有通知为已读
export async function POST(request: NextRequest) {
  try {
    const session = await auth();

    if (!session?.user?.id) {
      return NextResponse.json({ error: '未授权' }, { status: 401 });
    }

    const userId = session.user.id;
    const url = new URL(request.url);
    const path = url.pathname;
    
    // 处理"标记所有为已读"的请求
    if (path.endsWith('/mark-all-read')) {
      await prisma.notificationRecipient.updateMany({
        where: {
          userId,
          read: false,
        },
        data: {
          read: true,
        },
      });
      
      return new NextResponse(null, { status: 204 });
    }
    
    // 如果不是已知的POST端点，返回错误
    return NextResponse.json(
      { error: '未知的请求' },
      { status: 400 }
    );
  } catch (error) {
    console.error('处理通知请求失败:', error);
    return NextResponse.json(
      { error: '处理通知请求时出错' },
      { status: 500 }
    );
  }
} 